function loadProjectsTable() {
	$.getJSON("GetProjects").done(function(result) {
		$("#projects tbody").html("");			// clear table
	
		$.each(result.row, function(i, row) {
			if (sessionRoleName == "Team Member") {
				if (sessionProjectId == row.id) {
					appendDataToProjectsList(row);
				}
			} else {
				appendDataToProjectsList(row);
			}
		});
		
		setView();
		if (sessionRoleName == "Product Owner") {
			setSelection();
		}
	}).fail(function() {
		alert('Error loading data for projects table');
	});
}

function updateDataInProjectList(row) {
	var currentName = $("#" + row.id).find(".name-column").text();
	var isSelected = $("#" + row.id).find(".radio-button:checked").val();

	if (currentName == row.name) {
		$("#" + row.id).html(createTableRowString(false, row));
	}
	else {
		// if name change, delete old row and add new row
		$("#" + row.id).remove();
		insertRowSortedByName(row, 'projects', insertDataInProjectsList, appendDataToProjectsList);
	}
	
	if (isSelected) {
		$("#" + row.id).find(".radio-button").prop('checked',true);
	}

	setView();
}

function appendDataToProjectsList(row) {
	$("#projects tbody").append(createTableRowString(true, row));
}

function insertDataInProjectsList(insertBeforeThisRow, row) {
	$(insertBeforeThisRow).before(createTableRowString(true, row));
	setView();
}

function createTableRowString(withTR, row) {
	var tableColumns = '<td class="action-column">\n'
		+ '<button class="edit-button">Edit</button>\n'
		+ '<button class="delete-button">Delete</button>\n'
		+ '</td>\n'
		+ '<td class="select-column"><input class="radio-button" name="project" type="radio"></input></td>\n'
		+ '<td class="name-column">' + row.name	+ '</td>\n'
		+ '<td class="description-column">' + row.description + '</td>\n';
 
	if (withTR) {
		var tableRowString = '<tr id="' + row.id + '">\n'
			+ tableColumns
			+ '</tr>\n';
		
		return tableRowString;
	}
	
	return tableColumns;
}

function setView() {
	// hide edit and delete buttons as well as the select buttons if normal user
	// hide Add button
	if (sessionRoleName == "Team Member") {
		$(".action-column").hide();
		$(".select-column").hide();
		$("#add-project").hide();
	}
}

// selects radio button that matches the users current project.
function setSelection() {
	$('#projects tr').not('thead tr').each(function(index) {
		if ($(this).attr('id') == sessionProjectId) {
			$(this).find("input[type=radio]").prop("checked", true);
			return false;
		}
	});
}

function insertDataInProjectsList(insertBeforeThisRow, row) {
	$(insertBeforeThisRow).before(createTableRowString(true, row));
}

function validateProjectData(source, all_project_fields, id, name, previousName, description, project_tips) {
	var bValid = true;
	all_project_fields.removeClass("ui-state-error");
	
	bValid = bValid	&& checkLength(name, "name", 1, 50, project_tips);
	bValid = bValid	&& checkLength(description,	"description", 1, 250, project_tips);

	if (source === "ADD" || (source === "EDIT" && name.val() !== previousName)) {
		bValid = bValid && validateProjectNameDoesNotExist(name, project_tips);
	}

	return bValid;
}

$(function() {
    var name = $( "#name" ),
      description = $( "#description" ),
      all_project_fields = $( [] ).add( name ).add( description );
      project_tips = $( ".projectValidateTips" );

  	$("#project-dialog-form").dialog({
		autoOpen : false,
		height : 400,
		width : 550,
		modal : true
	});

    function closeProjectDialogBox(dialogBox) {
		all_project_fields.val("").removeClass("ui-state-error");
	    $("p.projectValidateTips").text('All form fields are required.');
	    $(dialogBox).dialog("close");
    }

    loadProjectsTable();
	
	$("#add-project").button().click(function() {
		$("#project-dialog-form").dialog('option', 'title', 'Add new project');
		$("#project-dialog-form").dialog({
			buttons : {
				"Add" : function() {
					all_project_fields.removeClass("ui-state-error");

					if (validateProjectData("ADD", all_project_fields, null, name, null, description, project_tips)) {
						$.post("AddProject", $("#project-form").serialize()).done(function(data) {
							var returnedData = jQuery.parseJSON(data);
						
							insertRowSortedByName(returnedData, 'projects', insertDataInProjectsList, appendDataToProjectsList);
						})
						.fail(function(data) {
							alert("Failed to add new project.");
						});

						$(this).dialog("close");
					}
				}
			},
			close : function() {
				closeProjectDialogBox(this);
			}
		});
		$("#project-dialog-form").dialog("open");
	});

	$(document).on("click", ".edit-button", function() {
		var project_id=$(this).closest('tr').attr('id'); // get project id from page
		var parameters = "project-id=" + project_id;
		var previousName = null;
		
		$.getJSON("GetProjectById", parameters).done(function(returnedData) {
			$("#project-dialog-form").data('id', returnedData.id);
			$('#name').val(returnedData.name);
			previousName = returnedData.name;
			$('#description').val(returnedData.description);
		}).fail(function() {
			alert('Error getting project data');
		});
		
		$("#project-dialog-form").dialog('option', 'title', 'Edit project id ' + project_id);

		$("#project-dialog-form").dialog({
			buttons : {
				"Update" : function() {
					if (validateProjectData("EDIT", all_project_fields, null, name, previousName, description, project_tips)) {
						id = $("#project-dialog-form").data('id');
						parameters = "project-id=" + id + "&" + $("#project-form").serialize();
						$.post("EditProject", parameters).done(function(data) {
							var returnedData = jQuery.parseJSON(data);
							updateDataInProjectList(returnedData);

							// if the current selected project name changed
							if (id == sessionProjectId) {
								setProjectIdAndName(sessionProjectId);
							}

						}).fail(function(data) {
							alert("Failed to update project.");
						});
						closeProjectDialogBox(this);
					}

				}
			},
			close : function() {
				closeProjectDialogBox(this);
			}
		});
		
		$("#project-dialog-form").dialog("open");
	});
	
	// delete button
	$(document).on("click", ".delete-button", function() {
		var project_id=$(this).closest('tr').attr('id'); // get project id from page
		var project_name = $(this).closest('tr').children('td.name-column').text();
		var isSelected = $(this).closest('tr').find("input[type=radio]").is(":checked"); 
		var confirmRemove = confirm('Are you sure you want to delete project ' + project_name
				+ ' (id '+ project_id + ') from the system? This will delete all sprints, user stories, tasks, and test cases'
				+ ' that are associated with the project and unassign team members from the project.');
		
		if (confirmRemove != true) return;
		
		var parameters = "project-id=" + project_id;

		$.post("DeleteProject", parameters).done(function(data) {
			var returnedData = jQuery.parseJSON(data);
			if (returnedData.status == true) {
				$('#' + project_id).remove();
			}
			else {
				alert("Error deleting project " + project_name);
			}
		}).fail(function() {
			alert('Error completing deleting project');
		});
		
		// if radio button was selected, then select current user's project and set project in title bar
		if (isSelected) {
			$.ajax({
				url: "GetTeamMemberData",
				dataType: 'json',
				async: false,
				data: { teamMemberId: sessionTeamMemberId },
				success: function(result) {
					$.each(result, function(i, row) {
						setProjectIdAndName(result.project_id);
						$('#' + result.project_id).find("input[type=radio]").prop("checked", true);
					});
				}
			}).fail(function() {
				alert('Error getting JSON for team member');
			});
		}
	});

	// radio button select
	$(document).on("click", ".radio-button", function() {
		var project_id=$(this).closest('tr').attr('id');
		
		setProjectIdAndName(project_id);
	});
});
